package definite.Guide.Book.JPopupMenu;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

public class PopupMenu {

	private static JMenuItem paste;

	// define Action Listener
	static class PopupActionListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			System.out.println("Selected : " + e.getActionCommand());
		}

	}

	static class changeListener implements ChangeListener {

		@Override
		public void stateChanged(ChangeEvent e) {
			AbstractButton button = (AbstractButton) e.getSource();
			ButtonModel model = button.getModel();
			boolean selected = model.isSelected();
			if (selected)
				paste.setEnabled(true);
		}
	}

	// define PopupMenu Listener
	static class MyPopupMenuListener implements PopupMenuListener {

		@Override
		public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
			System.out.println("Become VISIBLE");
		}

		@Override
		public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
			System.out.println("Become INVISIBLE");
		}

		@Override
		public void popupMenuCanceled(PopupMenuEvent e) {
			System.out.println("Canceled");
		}

	}

	public static void main(String[] args) {
		Runnable runner = new Runnable() {

			@Override
			public void run() {
				JFrame.setDefaultLookAndFeelDecorated(true);
				JFrame frame = new JFrame("JPopupMenu Sample");
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

				ActionListener actionListener = new PopupActionListener();
				PopupMenuListener popupMenuListener = new MyPopupMenuListener();
				ChangeListener changeListen = new changeListener();

				JPopupMenu popup = new JPopupMenu("Title");
				popup.addPopupMenuListener(popupMenuListener);

				JMenuItem cut = new JMenuItem("CUT");
				cut.addActionListener(actionListener);
				popup.add(cut);

				JMenuItem copy = new JMenuItem("COPY");
				copy.addActionListener(actionListener);
				copy.addChangeListener(changeListen);
				popup.add(copy);

				paste = new JMenuItem("PASTE");
				paste.addActionListener(actionListener);
				paste.setEnabled(false);
				popup.add(paste);

				popup.addSeparator();

				JMenuItem find = new JMenuItem("FIND");
				find.addActionListener(actionListener);
				popup.add(find);

				JPanel contentPane = (JPanel) frame.getContentPane();
				contentPane.setComponentPopupMenu(popup);

				frame.setSize(350, 250);
				frame.setLocationRelativeTo(null);
				frame.setVisible(true);
			}
		};

		EventQueue.invokeLater(runner);
	}
}
